<?php

/**
 * Représente un champ de type input
 *
 * @package cass
 * @author Mickaël CASTANHEIRO <mickael.castanheiro@gmail.com>
 * @version 1.0
 */

namespace cass\formulaire;

class InputFile extends Field {
    protected $properties;

    const TYPE_IMAGE = 0;
    const TYPE_FILE  = 9;

    /**
     * Indique le type de fichier
     */
    static private function getTypeOfFile($_file) { 
        $type = new \stdClass;
        if ( preg_match('!image/(png|gif|jpg|jpeg)!', $_file['type'], $matches) ) {
            $type->type = self::TYPE_IMAGE;
            $type->extension = $matches[1];
        }
        else {
            $type->type = self::TYPE_FILE;
            $type->extension = substr($_file['name'], strrpos($_file['name'], '.')+1);
        }
        return $type;
    }

    /**
     * Indique si le fichier est une image
     */
    public function isImage() { 
        if ( !empty($this->properties) AND !empty($this->properties->type) ) {
            return ($this->properties->type->type == self::TYPE_IMAGE);
        }
        return true; // Si pas de chargement, c'est une image
    }

    /**
     * Récupère les données en post (ou en get..)
     */
    public function bind() {
        $file = null; 
        if (!empty($_FILES) ) {
            if ( !empty($_FILES[$this->getSlug()]) AND !empty($_FILES[$this->getSlug()]['name']) ) { 
                $file = $_FILES[$this->getSlug()]; 
                $object = new \stdClass;
                $object->name = $file['name'];
                $object->type = self::getTypeOfFile($file);
                $object->path = $file['tmp_name'];
                $object->size = $file['size'];
                $this->properties = $object;
            }
        }
        $this->check();
        return $file;
    }

    /**
     * Vérifie la validité du champ
     */
    public function check() {
        if ($this->isRequired() AND empty($this->properties)) {
            $this->setError('Le champ est requis');
        }
    }

    /**
     * Charge le fichier dans le répertoire destiné
     * @param <string> $_directory Répertoire de destination
     */
    public function upload($_directory) { 
        do {
            $name = randomString(rand(5,11)) . '.' . $this->properties->type->extension;
        } while(file_exists(__PATH__ . $_directory . $name));

        move_uploaded_file($this->properties->path, __PATH__ . $_directory . $name);
        return $_directory . $name;
    }
}

?>
